<!-- HTML header for doxygen 1.8.6-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<title>OpenCV: Machine Learning Overview</title>
<link href="../../opencv.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../jquery.js"></script>
<script type="text/javascript" src="../../dynsections.js"></script>
<script type="text/javascript" src="../../tutorial-utils.js"></script>
<link href="../../search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../search/searchdata.js"></script>
<script type="text/javascript" src="../../search/search.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js", "TeX/AMSmath.js", "TeX/AMSsymbols.js"],
    jax: ["input/TeX","output/HTML-CSS"],
});
//<![CDATA[
MathJax.Hub.Config(
{
  TeX: {
      Macros: {
          matTT: [ "\\[ \\left|\\begin{array}{ccc} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{array}\\right| \\]", 9],
          fork: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ \\end{array} \\right.", 4],
          forkthree: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ \\end{array} \\right.", 6],
          forkfour: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ #7 & \\mbox{#8}\\\\ \\end{array} \\right.", 8],
          vecthree: ["\\begin{bmatrix} #1\\\\ #2\\\\ #3 \\end{bmatrix}", 3],
          vecthreethree: ["\\begin{bmatrix} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{bmatrix}", 9],
          cameramatrix: ["#1 = \\begin{bmatrix} f_x & 0 & c_x\\\\ 0 & f_y & c_y\\\\ 0 & 0 & 1 \\end{bmatrix}", 1],
          distcoeffs: ["(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \\tau_x, \\tau_y]]]]) \\text{ of 4, 5, 8, 12 or 14 elements}"],
          distcoeffsfisheye: ["(k_1, k_2, k_3, k_4)"],
          hdotsfor: ["\\dots", 1],
          mathbbm: ["\\mathbb{#1}", 1],
          bordermatrix: ["\\matrix{#1}", 1]
      }
  }
}
);
//]]>
</script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js"></script>
<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
<link href="../../stylesheet.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<!--#include virtual="/google-search.html"-->
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectlogo"><img alt="Logo" src="../../opencv-logo-small.png"/></td>
  <td style="padding-left: 0.5em;">
   <div id="projectname">OpenCV
   &#160;<span id="projectnumber">4.5.2</span>
   </div>
   <div id="projectbrief">Open Source Computer Vision</div>
  </td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "../../search",false,'Search');
</script>
<script type="text/javascript" src="../../menudata.js"></script>
<script type="text/javascript" src="../../menu.js"></script>
<script type="text/javascript">
$(function() {
  initMenu('../../',true,false,'search.php','Search');
  $(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" 
        name="MSearchResults" id="MSearchResults">
</iframe>
</div>

</div><!-- top -->
<div class="header">
  <div class="headertitle">
<div class="title">Machine Learning Overview </div>  </div>
</div><!--header-->
<div class="contents">
<div class="toc"><h3>Table of Contents</h3>
<ul><li class="level1"><a href="#ml_intro_data">Training Data </a></li>
<li class="level1"><a href="#ml_intro_bayes">Normal Bayes Classifier </a></li>
<li class="level1"><a href="#ml_intro_knn">K-Nearest Neighbors </a></li>
<li class="level1"><a href="#ml_intro_svm">Support Vector Machines </a><ul><li class="level2"><a href="#ml_intro_svm_predict">Prediction with SVM </a></li>
</ul>
</li>
<li class="level1"><a href="#ml_intro_trees">Decision Trees </a><ul><li class="level2"><a href="#ml_intro_trees_predict">Predicting with Decision Trees </a></li>
<li class="level2"><a href="#ml_intro_trees_train">Training Decision Trees </a></li>
<li class="level2"><a href="#ml_intro_trees_var">Variable Importance </a></li>
</ul>
</li>
<li class="level1"><a href="#ml_intro_boost">Boosting </a><ul><li class="level2"><a href="#ml_intro_boost_predict">Prediction with Boost </a></li>
</ul>
</li>
<li class="level1"><a href="#ml_intro_rtrees">Random Trees </a></li>
<li class="level1"><a href="#ml_intro_em">Expectation Maximization </a></li>
<li class="level1"><a href="#ml_intro_ann">Neural Networks </a></li>
<li class="level1"><a href="#ml_intro_lr">Logistic Regression </a></li>
</ul>
</div>
<div class="textblock"><h1><a class="anchor" id="ml_intro_data"></a>
Training Data </h1>
<p>In machine learning algorithms there is notion of training data. Training data includes several components:</p>
<ul>
<li>A set of training samples. Each training sample is a vector of values (in Computer Vision it's sometimes referred to as feature vector). Usually all the vectors have the same number of components (features); OpenCV ml module assumes that. Each feature can be ordered (i.e. its values are floating-point numbers that can be compared with each other and strictly ordered, i.e. sorted) or categorical (i.e. its value belongs to a fixed set of values that can be integers, strings etc.).</li>
<li>Optional set of responses corresponding to the samples. Training data with no responses is used in unsupervised learning algorithms that learn structure of the supplied data based on distances between different samples. Training data with responses is used in supervised learning algorithms, which learn the function mapping samples to responses. Usually the responses are scalar values, ordered (when we deal with regression problem) or categorical (when we deal with classification problem; in this case the responses are often called "labels"). Some algorithms, most noticeably Neural networks, can handle not only scalar, but also multi-dimensional or vector responses.</li>
<li>Another optional component is the mask of missing measurements. Most algorithms require all the components in all the training samples be valid, but some other algorithms, such as decision trees, can handle the cases of missing measurements.</li>
<li>In the case of classification problem user may want to give different weights to different classes. This is useful, for example, when:<ul>
<li>user wants to shift prediction accuracy towards lower false-alarm rate or higher hit-rate.</li>
<li>user wants to compensate for significantly different amounts of training samples from different classes.</li>
</ul>
</li>
<li>In addition to that, each training sample may be given a weight, if user wants the algorithm to pay special attention to certain training samples and adjust the training model accordingly.</li>
<li>Also, user may wish not to use the whole training data at once, but rather use parts of it, e.g. to do parameter optimization via cross-validation procedure.</li>
</ul>
<p>As you can see, training data can have rather complex structure; besides, it may be very big and/or not entirely available, so there is need to make abstraction for this concept. In OpenCV ml there is <a class="el" href="../../dc/d32/classcv_1_1ml_1_1TrainData.html" title="Class encapsulating training data. ">cv::ml::TrainData</a> class for that.</p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="../../dc/d32/classcv_1_1ml_1_1TrainData.html" title="Class encapsulating training data. ">cv::ml::TrainData</a></dd></dl>
<h1><a class="anchor" id="ml_intro_bayes"></a>
Normal Bayes Classifier </h1>
<p>This simple classification model assumes that feature vectors from each class are normally distributed (though, not necessarily independently distributed). So, the whole data distribution function is assumed to be a Gaussian mixture, one component per class. Using the training data the algorithm estimates mean vectors and covariance matrices for every class, and then it uses them for prediction.</p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="../../d4/d8e/classcv_1_1ml_1_1NormalBayesClassifier.html" title="Bayes classifier for normally distributed data. ">cv::ml::NormalBayesClassifier</a></dd></dl>
<h1><a class="anchor" id="ml_intro_knn"></a>
K-Nearest Neighbors </h1>
<p>The algorithm caches all training samples and predicts the response for a new sample by analyzing a certain number (<b>K</b>) of the nearest neighbors of the sample using voting, calculating weighted sum, and so on. The method is sometimes referred to as "learning by example" because for prediction it looks for the feature vector with a known response that is closest to the given vector.</p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="../../dd/de1/classcv_1_1ml_1_1KNearest.html" title="The class implements K-Nearest Neighbors model. ">cv::ml::KNearest</a></dd></dl>
<h1><a class="anchor" id="ml_intro_svm"></a>
Support Vector Machines </h1>
<p>Originally, support vector machines (SVM) was a technique for building an optimal binary (2-class) classifier. Later the technique was extended to regression and clustering problems. SVM is a partial case of kernel-based methods. It maps feature vectors into a higher-dimensional space using a kernel function and builds an optimal linear discriminating function in this space or an optimal hyper- plane that fits into the training data. In case of SVM, the kernel is not defined explicitly. Instead, a distance between any 2 points in the hyper-space needs to be defined.</p>
<p>The solution is optimal, which means that the margin between the separating hyper-plane and the nearest feature vectors from both classes (in case of 2-class classifier) is maximal. The feature vectors that are the closest to the hyper-plane are called <em>support vectors</em>, which means that the position of other vectors does not affect the hyper-plane (the decision function).</p>
<p>SVM implementation in OpenCV is based on <a class="el" href="../../d0/de3/citelist.html#CITEREF_LibSVM">[43]</a></p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="../../d1/d2d/classcv_1_1ml_1_1SVM.html" title="Support Vector Machines. ">cv::ml::SVM</a></dd></dl>
<h2><a class="anchor" id="ml_intro_svm_predict"></a>
Prediction with SVM </h2>
<p>StatModel::predict(samples, results, flags) should be used. Pass flags=StatModel::RAW_OUTPUT to get the raw response from SVM (in the case of regression, 1-class or 2-class classification problem).</p>
<h1><a class="anchor" id="ml_intro_trees"></a>
Decision Trees </h1>
<p>The ML classes discussed in this section implement Classification and Regression Tree algorithms described in <a class="el" href="../../d0/de3/citelist.html#CITEREF_Breiman84">[34]</a> .</p>
<p>The class <a class="el" href="../../d8/d89/classcv_1_1ml_1_1DTrees.html" title="The class represents a single decision tree or a collection of decision trees. ">cv::ml::DTrees</a> represents a single decision tree or a collection of decision trees. It's also a base class for RTrees and Boost.</p>
<p>A decision tree is a binary tree (tree where each non-leaf node has two child nodes). It can be used either for classification or for regression. For classification, each tree leaf is marked with a class label; multiple leaves may have the same label. For regression, a constant is also assigned to each tree leaf, so the approximation function is piecewise constant.</p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="../../d8/d89/classcv_1_1ml_1_1DTrees.html" title="The class represents a single decision tree or a collection of decision trees. ">cv::ml::DTrees</a></dd></dl>
<h2><a class="anchor" id="ml_intro_trees_predict"></a>
Predicting with Decision Trees </h2>
<p>To reach a leaf node and to obtain a response for the input feature vector, the prediction procedure starts with the root node. From each non-leaf node the procedure goes to the left (selects the left child node as the next observed node) or to the right based on the value of a certain variable whose index is stored in the observed node. The following variables are possible:</p>
<ul>
<li><b>Ordered variables.</b> The variable value is compared with a threshold that is also stored in the node. If the value is less than the threshold, the procedure goes to the left. Otherwise, it goes to the right. For example, if the weight is less than 1 kilogram, the procedure goes to the left, else to the right.</li>
<li><b>Categorical variables.</b> A discrete variable value is tested to see whether it belongs to a certain subset of values (also stored in the node) from a limited set of values the variable could take. If it does, the procedure goes to the left. Otherwise, it goes to the right. For example, if the color is green or red, go to the left, else to the right.</li>
</ul>
<p>So, in each node, a pair of entities (variable_index , <code>decision_rule (threshold/subset)</code> ) is used. This pair is called a <em>split</em> (split on the variable variable_index ). Once a leaf node is reached, the value assigned to this node is used as the output of the prediction procedure.</p>
<p>Sometimes, certain features of the input vector are missed (for example, in the darkness it is difficult to determine the object color), and the prediction procedure may get stuck in the certain node (in the mentioned example, if the node is split by color). To avoid such situations, decision trees use so-called <em>surrogate splits</em>. That is, in addition to the best "primary" split, every tree node may also be split to one or more other variables with nearly the same results.</p>
<h2><a class="anchor" id="ml_intro_trees_train"></a>
Training Decision Trees </h2>
<p>The tree is built recursively, starting from the root node. All training data (feature vectors and responses) is used to split the root node. In each node the optimum decision rule (the best "primary" split) is found based on some criteria. In machine learning, gini "purity" criteria are used for classification, and sum of squared errors is used for regression. Then, if necessary, the surrogate splits are found. They resemble the results of the primary split on the training data. All the data is divided using the primary and the surrogate splits (like it is done in the prediction procedure) between the left and the right child node. Then, the procedure recursively splits both left and right nodes. At each node the recursive procedure may stop (that is, stop splitting the node further) in one of the following cases:</p>
<ul>
<li>Depth of the constructed tree branch has reached the specified maximum value.</li>
<li>Number of training samples in the node is less than the specified threshold when it is not statistically representative to split the node further.</li>
<li>All the samples in the node belong to the same class or, in case of regression, the variation is too small.</li>
<li>The best found split does not give any noticeable improvement compared to a random choice.</li>
</ul>
<p>When the tree is built, it may be pruned using a cross-validation procedure, if necessary. That is, some branches of the tree that may lead to the model overfitting are cut off. Normally, this procedure is only applied to standalone decision trees. Usually tree ensembles build trees that are small enough and use their own protection schemes against overfitting.</p>
<h2><a class="anchor" id="ml_intro_trees_var"></a>
Variable Importance </h2>
<p>Besides the prediction that is an obvious use of decision trees, the tree can be also used for various data analyses. One of the key properties of the constructed decision tree algorithms is an ability to compute the importance (relative decisive power) of each variable. For example, in a spam filter that uses a set of words occurred in the message as a feature vector, the variable importance rating can be used to determine the most "spam-indicating" words and thus help keep the dictionary size reasonable.</p>
<p>Importance of each variable is computed over all the splits on this variable in the tree, primary and surrogate ones. Thus, to compute variable importance correctly, the surrogate splits must be enabled in the training parameters, even if there is no missing data.</p>
<h1><a class="anchor" id="ml_intro_boost"></a>
Boosting </h1>
<p>A common machine learning task is supervised learning. In supervised learning, the goal is to learn the functional relationship \(F: y = F(x)\) between the input \(x\) and the output \(y\) . Predicting the qualitative output is called <em>classification</em>, while predicting the quantitative output is called <em>regression</em>.</p>
<p>Boosting is a powerful learning concept that provides a solution to the supervised classification learning task. It combines the performance of many "weak" classifiers to produce a powerful committee <a class="el" href="../../d0/de3/citelist.html#CITEREF_HTF01">[249]</a> . A weak classifier is only required to be better than chance, and thus can be very simple and computationally inexpensive. However, many of them smartly combine results to a strong classifier that often outperforms most "monolithic" strong classifiers such as SVMs and Neural Networks.</p>
<p>Decision trees are the most popular weak classifiers used in boosting schemes. Often the simplest decision trees with only a single split node per tree (called stumps ) are sufficient.</p>
<p>The boosted model is based on \(N\) training examples \({(x_i,y_i)}1N\) with \(x_i \in{R^K}\) and \(y_i \in{-1, +1}\) . \(x_i\) is a \(K\) -component vector. Each component encodes a feature relevant to the learning task at hand. The desired two-class output is encoded as -1 and +1.</p>
<p>Different variants of boosting are known as Discrete Adaboost, Real AdaBoost, LogitBoost, and Gentle AdaBoost <a class="el" href="../../d0/de3/citelist.html#CITEREF_FHT98">[82]</a> . All of them are very similar in their overall structure. Therefore, this chapter focuses only on the standard two-class Discrete AdaBoost algorithm, outlined below. Initially the same weight is assigned to each sample (step 2). Then, a weak classifier \(f_{m(x)}\) is trained on the weighted training data (step 3a). Its weighted training error and scaling factor \(c_m\) is computed (step 3b). The weights are increased for training samples that have been misclassified (step 3c). All weights are then normalized, and the process of finding the next weak classifier continues for another \(M\) -1 times. The final classifier \(F(x)\) is the sign of the weighted sum over the individual weak classifiers (step 4).</p>
<p><b>Two-class Discrete AdaBoost Algorithm</b></p>
<ul>
<li>Set \(N\) examples \({(x_i,y_i)}1N\) with \(x_i \in{R^K}, y_i \in{-1, +1}\) .</li>
<li>Assign weights as \(w_i = 1/N, i = 1,...,N\) .</li>
<li>Repeat for \(m = 1,2,...,M\) :<ul>
<li>Fit the classifier \(f_m(x) \in{-1,1}\), using weights \(w_i\) on the training data.</li>
<li>Compute \(err_m = E_w [1_{(y \neq f_m(x))}], c_m = log((1 - err_m)/err_m)\) .</li>
<li>Set \(w_i \Leftarrow w_i exp[c_m 1_{(y_i \neq f_m(x_i))}], i = 1,2,...,N,\) and renormalize so that \(\Sigma i w_i = 1\) .</li>
</ul>
</li>
<li>Classify new samples <em>x</em> using the formula: \(\textrm{sign} (\Sigma m = 1M c_m f_m(x))\) .</li>
</ul>
<dl class="section note"><dt>Note</dt><dd>Similar to the classical boosting methods, the current implementation supports two-class classifiers only. For M &gt; 2 classes, there is the <b>AdaBoost.MH</b> algorithm (described in <a class="el" href="../../d0/de3/citelist.html#CITEREF_FHT98">[82]</a>) that reduces the problem to the two-class problem, yet with a much larger training set.</dd></dl>
<p>To reduce computation time for boosted models without substantially losing accuracy, the influence trimming technique can be employed. As the training algorithm proceeds and the number of trees in the ensemble is increased, a larger number of the training samples are classified correctly and with increasing confidence, thereby those samples receive smaller weights on the subsequent iterations. Examples with a very low relative weight have a small impact on the weak classifier training. Thus, such examples may be excluded during the weak classifier training without having much effect on the induced classifier. This process is controlled with the weight_trim_rate parameter. Only examples with the summary fraction weight_trim_rate of the total weight mass are used in the weak classifier training. Note that the weights for <b>all</b> training examples are recomputed at each training iteration. Examples deleted at a particular iteration may be used again for learning some of the weak classifiers further <a class="el" href="../../d0/de3/citelist.html#CITEREF_FHT98">[82]</a></p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="../../d6/d7a/classcv_1_1ml_1_1Boost.html" title="Boosted tree classifier derived from DTrees. ">cv::ml::Boost</a></dd></dl>
<h2><a class="anchor" id="ml_intro_boost_predict"></a>
Prediction with Boost </h2>
<p>StatModel::predict(samples, results, flags) should be used. Pass flags=StatModel::RAW_OUTPUT to get the raw sum from Boost classifier.</p>
<h1><a class="anchor" id="ml_intro_rtrees"></a>
Random Trees </h1>
<p>Random trees have been introduced by Leo Breiman and Adele Cutler: <a href="http://www.stat.berkeley.edu/users/breiman/RandomForests/">http://www.stat.berkeley.edu/users/breiman/RandomForests/</a> . The algorithm can deal with both classification and regression problems. Random trees is a collection (ensemble) of tree predictors that is called <em>forest</em> further in this section (the term has been also introduced by L. Breiman). The classification works as follows: the random trees classifier takes the input feature vector, classifies it with every tree in the forest, and outputs the class label that received the majority of "votes". In case of a regression, the classifier response is the average of the responses over all the trees in the forest.</p>
<p>All the trees are trained with the same parameters but on different training sets. These sets are generated from the original training set using the bootstrap procedure: for each training set, you randomly select the same number of vectors as in the original set ( =N ). The vectors are chosen with replacement. That is, some vectors will occur more than once and some will be absent. At each node of each trained tree, not all the variables are used to find the best split, but a random subset of them. With each node a new subset is generated. However, its size is fixed for all the nodes and all the trees. It is a training parameter set to \(\sqrt{number\_of\_variables}\) by default. None of the built trees are pruned.</p>
<p>In random trees there is no need for any accuracy estimation procedures, such as cross-validation or bootstrap, or a separate test set to get an estimate of the training error. The error is estimated internally during the training. When the training set for the current tree is drawn by sampling with replacement, some vectors are left out (so-called <em>oob (out-of-bag) data</em> ). The size of oob data is about N/3 . The classification error is estimated by using this oob-data as follows:</p>
<ul>
<li>Get a prediction for each vector, which is oob relative to the i-th tree, using the very i-th tree.</li>
<li>After all the trees have been trained, for each vector that has ever been oob, find the class-<em>winner</em> for it (the class that has got the majority of votes in the trees where the vector was oob) and compare it to the ground-truth response.</li>
<li>Compute the classification error estimate as a ratio of the number of misclassified oob vectors to all the vectors in the original data. In case of regression, the oob-error is computed as the squared error for oob vectors difference divided by the total number of vectors.</li>
</ul>
<p>For the random trees usage example, please, see letter_recog.cpp sample in OpenCV distribution.</p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="../../d0/d65/classcv_1_1ml_1_1RTrees.html" title="The class implements the random forest predictor. ">cv::ml::RTrees</a></dd></dl>
<p><b>References:</b></p>
<ul>
<li><em>Machine Learning</em>, Wald I, July 2002. <a href="http://stat-www.berkeley.edu/users/breiman/wald2002-1.pdf">http://stat-www.berkeley.edu/users/breiman/wald2002-1.pdf</a></li>
<li><em>Looking Inside the Black Box</em>, Wald II, July 2002. <a href="http://stat-www.berkeley.edu/users/breiman/wald2002-2.pdf">http://stat-www.berkeley.edu/users/breiman/wald2002-2.pdf</a></li>
<li><em>Software for the Masses</em>, Wald III, July 2002. <a href="http://stat-www.berkeley.edu/users/breiman/wald2002-3.pdf">http://stat-www.berkeley.edu/users/breiman/wald2002-3.pdf</a></li>
<li>And other articles from the web site <a href="http://www.stat.berkeley.edu/users/breiman/RandomForests/cc_home.htm">http://www.stat.berkeley.edu/users/breiman/RandomForests/cc_home.htm</a></li>
</ul>
<h1><a class="anchor" id="ml_intro_em"></a>
Expectation Maximization </h1>
<p>The Expectation Maximization(EM) algorithm estimates the parameters of the multivariate probability density function in the form of a Gaussian mixture distribution with a specified number of mixtures.</p>
<p>Consider the set of the N feature vectors { \(x_1, x_2,...,x_{N}\) } from a d-dimensional Euclidean space drawn from a Gaussian mixture:</p>
<p class="formulaDsp">
\[p(x;a_k,S_k, \pi _k) = \sum _{k=1}^{m} \pi _kp_k(x), \quad \pi _k \geq 0, \quad \sum _{k=1}^{m} \pi _k=1,\]
</p>
<p class="formulaDsp">
\[p_k(x)= \varphi (x;a_k,S_k)= \frac{1}{(2\pi)^{d/2}\mid{S_k}\mid^{1/2}} exp \left \{ - \frac{1}{2} (x-a_k)^TS_k^{-1}(x-a_k) \right \} ,\]
</p>
<p>where \(m\) is the number of mixtures, \(p_k\) is the normal distribution density with the mean \(a_k\) and covariance matrix \(S_k\), \(\pi_k\) is the weight of the k-th mixture. Given the number of mixtures \(M\) and the samples \(x_i\), \(i=1..N\) the algorithm finds the maximum- likelihood estimates (MLE) of all the mixture parameters, that is, \(a_k\), \(S_k\) and \(\pi_k\) :</p>
<p class="formulaDsp">
\[L(x, \theta )=logp(x, \theta )= \sum _{i=1}^{N}log \left ( \sum _{k=1}^{m} \pi _kp_k(x) \right ) \to \max _{ \theta \in \Theta },\]
</p>
<p class="formulaDsp">
\[\Theta = \left \{ (a_k,S_k, \pi _k): a_k \in \mathbbm{R} ^d,S_k=S_k^T&gt;0,S_k \in \mathbbm{R} ^{d \times d}, \pi _k \geq 0, \sum _{k=1}^{m} \pi _k=1 \right \} .\]
</p>
<p>The EM algorithm is an iterative procedure. Each iteration includes two steps. At the first step (Expectation step or E-step), you find a probability \(p_{i,k}\) (denoted \(\alpha_{i,k}\) in the formula below) of sample i to belong to mixture k using the currently available mixture parameter estimates:</p>
<p class="formulaDsp">
\[\alpha _{ki} = \frac{\pi_k\varphi(x;a_k,S_k)}{\sum\limits_{j=1}^{m}\pi_j\varphi(x;a_j,S_j)} .\]
</p>
<p>At the second step (Maximization step or M-step), the mixture parameter estimates are refined using the computed probabilities:</p>
<p class="formulaDsp">
\[\pi _k= \frac{1}{N} \sum _{i=1}^{N} \alpha _{ki}, \quad a_k= \frac{\sum\limits_{i=1}^{N}\alpha_{ki}x_i}{\sum\limits_{i=1}^{N}\alpha_{ki}} , \quad S_k= \frac{\sum\limits_{i=1}^{N}\alpha_{ki}(x_i-a_k)(x_i-a_k)^T}{\sum\limits_{i=1}^{N}\alpha_{ki}}\]
</p>
<p>Alternatively, the algorithm may start with the M-step when the initial values for \(p_{i,k}\) can be provided. Another alternative when \(p_{i,k}\) are unknown is to use a simpler clustering algorithm to pre-cluster the input samples and thus obtain initial \(p_{i,k}\) . Often (including machine learning) the k-means algorithm is used for that purpose.</p>
<p>One of the main problems of the EM algorithm is a large number of parameters to estimate. The majority of the parameters reside in covariance matrices, which are \(d \times d\) elements each where \(d\) is the feature space dimensionality. However, in many practical problems, the covariance matrices are close to diagonal or even to \(\mu_k*I\) , where \(I\) is an identity matrix and \(\mu_k\) is a mixture-dependent "scale" parameter. So, a robust computation scheme could start with harder constraints on the covariance matrices and then use the estimated parameters as an input for a less constrained optimization problem (often a diagonal covariance matrix is already a good enough approximation).</p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="../../d1/dfb/classcv_1_1ml_1_1EM.html" title="The class implements the Expectation Maximization algorithm. ">cv::ml::EM</a></dd></dl>
<p>References:</p><ul>
<li>Bilmes98 J. A. Bilmes. <em>A Gentle Tutorial of the EM Algorithm and its Application to Parameter Estimation for Gaussian Mixture and Hidden Markov Models</em>. Technical Report TR-97-021, International Computer Science Institute and Computer Science Division, University of California at Berkeley, April 1998.</li>
</ul>
<h1><a class="anchor" id="ml_intro_ann"></a>
Neural Networks </h1>
<p>ML implements feed-forward artificial neural networks or, more particularly, multi-layer perceptrons (MLP), the most commonly used type of neural networks. MLP consists of the input layer, output layer, and one or more hidden layers. Each layer of MLP includes one or more neurons directionally linked with the neurons from the previous and the next layer. The example below represents a 3-layer perceptron with three inputs, two outputs, and the hidden layer including five neurons:</p>
<div class="image">
<img src="../../mlp.png" alt="mlp.png"/>
<div class="caption">
image</div></div>
<p> All the neurons in MLP are similar. Each of them has several input links (it takes the output values from several neurons in the previous layer as input) and several output links (it passes the response to several neurons in the next layer). The values retrieved from the previous layer are summed up with certain weights, individual for each neuron, plus the bias term. The sum is transformed using the activation function \(f\) that may be also different for different neurons.</p>
<div class="image">
<img src="../../neuron_model.png" alt="neuron_model.png"/>
<div class="caption">
image</div></div>
<p> In other words, given the outputs \(x_j\) of the layer \(n\) , the outputs \(y_i\) of the layer \(n+1\) are computed as:</p>
<p class="formulaDsp">
\[u_i = \sum _j (w^{n+1}_{i,j}*x_j) + w^{n+1}_{i,bias}\]
</p>
<p class="formulaDsp">
\[y_i = f(u_i)\]
</p>
<p>Different activation functions may be used. ML implements three standard functions:</p>
<ul>
<li>Identity function ( <a class="el" href="../../d0/dce/classcv_1_1ml_1_1ANN__MLP.html#ade71470ec8814021728f8b31b09773b0a5cafa9aa38d3f60f8238e867a4a98e0a">cv::ml::ANN_MLP::IDENTITY</a> ): \(f(x)=x\)</li>
<li><p class="startli">Symmetrical sigmoid ( <a class="el" href="../../d0/dce/classcv_1_1ml_1_1ANN__MLP.html#ade71470ec8814021728f8b31b09773b0a90410002f1e243d35dca234f859f270e">cv::ml::ANN_MLP::SIGMOID_SYM</a> ): \(f(x)=\beta*(1-e^{-\alpha x})/(1+e^{-\alpha x}\) ), which is the default choice for MLP. The standard sigmoid with \(\beta =1, \alpha =1\) is shown below:</p>
<div class="image">
<img src="../../sigmoid_bipolar.png" alt="sigmoid_bipolar.png"/>
<div class="caption">
image</div></div>
</li>
<li>Gaussian function ( <a class="el" href="../../d0/dce/classcv_1_1ml_1_1ANN__MLP.html#ade71470ec8814021728f8b31b09773b0ae3d886f16c8018eebf26d8d75a90dd7e">cv::ml::ANN_MLP::GAUSSIAN</a> ): \(f(x)=\beta e^{-\alpha x*x}\) , which is not completely supported at the moment.</li>
</ul>
<p>In ML, all the neurons have the same activation functions, with the same free parameters ( \(\alpha, \beta\) ) that are specified by user and are not altered by the training algorithms.</p>
<p>So, the whole trained network works as follows:</p>
<ol type="1">
<li>Take the feature vector as input. The vector size is equal to the size of the input layer.</li>
<li>Pass values as input to the first hidden layer.</li>
<li>Compute outputs of the hidden layer using the weights and the activation functions.</li>
<li>Pass outputs further downstream until you compute the output layer.</li>
</ol>
<p>So, to compute the network, you need to know all the weights \(w^{n+1)}_{i,j}\) . The weights are computed by the training algorithm. The algorithm takes a training set, multiple input vectors with the corresponding output vectors, and iteratively adjusts the weights to enable the network to give the desired response to the provided input vectors.</p>
<p>The larger the network size (the number of hidden layers and their sizes) is, the more the potential network flexibility is. The error on the training set could be made arbitrarily small. But at the same time the learned network also "learns" the noise present in the training set, so the error on the test set usually starts increasing after the network size reaches a limit. Besides, the larger networks are trained much longer than the smaller ones, so it is reasonable to pre-process the data, using <a class="el" href="../../d3/d8d/classcv_1_1PCA.html" title="Principal Component Analysis. ">cv::PCA</a> or similar technique, and train a smaller network on only essential features.</p>
<p>Another MLP feature is an inability to handle categorical data as is. However, there is a workaround. If a certain feature in the input or output (in case of n -class classifier for \(n&gt;2\) ) layer is categorical and can take \(M&gt;2\) different values, it makes sense to represent it as a binary tuple of M elements, where the i -th element is 1 if and only if the feature is equal to the i -th value out of M possible. It increases the size of the input/output layer but speeds up the training algorithm convergence and at the same time enables "fuzzy" values of such variables, that is, a tuple of probabilities instead of a fixed value.</p>
<p>ML implements two algorithms for training MLP's. The first algorithm is a classical random sequential back-propagation algorithm. The second (default) one is a batch RPROP algorithm.</p>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="../../d0/dce/classcv_1_1ml_1_1ANN__MLP.html" title="Artificial Neural Networks - Multi-Layer Perceptrons. ">cv::ml::ANN_MLP</a></dd></dl>
<h1><a class="anchor" id="ml_intro_lr"></a>
Logistic Regression </h1>
<p>ML implements logistic regression, which is a probabilistic classification technique. Logistic Regression is a binary classification algorithm which is closely related to Support Vector Machines (SVM). Like SVM, Logistic Regression can be extended to work on multi-class classification problems like digit recognition (i.e. recognizing digits like 0,1 2, 3,... from the given images). This version of Logistic Regression supports both binary and multi-class classifications (for multi-class it creates a multiple 2-class classifiers). In order to train the logistic regression classifier, Batch Gradient Descent and Mini-Batch Gradient Descent algorithms are used (see <a href="http://en.wikipedia.org/wiki/Gradient_descent_optimization">http://en.wikipedia.org/wiki/Gradient_descent_optimization</a>). Logistic Regression is a discriminative classifier (see <a href="http://www.cs.cmu.edu/~tom/NewChapters.html">http://www.cs.cmu.edu/~tom/NewChapters.html</a> for more details). Logistic Regression is implemented as a C++ class in LogisticRegression.</p>
<p>In Logistic Regression, we try to optimize the training parameter \(\theta\) such that the hypothesis \(0 \leq h_\theta(x) \leq 1\) is achieved. We have \(h_\theta(x) = g(h_\theta(x))\) and \(g(z) = \frac{1}{1+e^{-z}}\) as the logistic or sigmoid function. The term "Logistic" in Logistic Regression refers to this function. For given data of a binary classification problem of classes 0 and 1, one can determine that the given data instance belongs to class 1 if \(h_\theta(x) \geq 0.5\) or class 0 if \(h_\theta(x) &lt; 0.5\) .</p>
<p>In Logistic Regression, choosing the right parameters is of utmost importance for reducing the training error and ensuring high training accuracy:</p>
<ul>
<li>The learning rate can be set with <a class="el" href="../../d6/df9/classcv_1_1ml_1_1LogisticRegression.html#a1d050c28ca1fba9439961f76ba526cec">setLearningRate</a> method. It determines how fast we approach the solution. It is a positive real number.</li>
<li>Optimization algorithms like Batch Gradient Descent and Mini-Batch Gradient Descent are supported in LogisticRegression. It is important that we mention the number of iterations these optimization algorithms have to run. The number of iterations can be set with <a class="el" href="../../d6/df9/classcv_1_1ml_1_1LogisticRegression.html#a77ecde450d828a236b77681f6cd375d8">setIterations</a>. This parameter can be thought as number of steps taken and learning rate specifies if it is a long step or a short step. This and previous parameter define how fast we arrive at a possible solution.</li>
<li>In order to compensate for overfitting regularization is performed, which can be enabled with <a class="el" href="../../d6/df9/classcv_1_1ml_1_1LogisticRegression.html#abfe3f52c9e90a631b37baba63af21a49">setRegularization</a>. One can specify what kind of regularization has to be performed by passing one of <a class="el" href="../../d6/df9/classcv_1_1ml_1_1LogisticRegression.html#ac3b362508385fbbeffac160e686d9c86">regularization kinds</a> to this method.</li>
<li>Logistic regression implementation provides a choice of 2 training methods with Batch Gradient Descent or the MiniBatch Gradient Descent. To specify this, call <a class="el" href="../../d6/df9/classcv_1_1ml_1_1LogisticRegression.html#a18934b829da316ac02d18d5a413ab221">setTrainMethod</a> with either <a class="el" href="../../d6/df9/classcv_1_1ml_1_1LogisticRegression.html#a11394898c4732995dd3af8a665f92894af196a9e88d65d52f36e994b3e3e3a440">LogisticRegression::BATCH</a> or <a class="el" href="../../d6/df9/classcv_1_1ml_1_1LogisticRegression.html#a11394898c4732995dd3af8a665f92894aabdf956ee52b567744e53767d0f41df1">LogisticRegression::MINI_BATCH</a>. If training method is set to <a class="el" href="../../d6/df9/classcv_1_1ml_1_1LogisticRegression.html#a11394898c4732995dd3af8a665f92894aabdf956ee52b567744e53767d0f41df1">MINI_BATCH</a>, the size of the mini batch has to be to a positive integer set with <a class="el" href="../../d6/df9/classcv_1_1ml_1_1LogisticRegression.html#a1ba3ea00151b9671534e65fe936402b2">setMiniBatchSize</a>.</li>
</ul>
<p>A sample set of training parameters for the Logistic Regression classifier can be initialized as follows: </p><div class="fragment"><div class="line">    Ptr&lt;LogisticRegression&gt; lr1 = LogisticRegression::create();</div><div class="line">    lr1-&gt;setLearningRate(0.001);</div><div class="line">    lr1-&gt;setIterations(10);</div><div class="line">    lr1-&gt;setRegularization(LogisticRegression::REG_L2);</div><div class="line">    lr1-&gt;setTrainMethod(LogisticRegression::BATCH);</div><div class="line">    lr1-&gt;setMiniBatchSize(1);</div></div><!-- fragment --> <dl class="section see"><dt>See also</dt><dd><a class="el" href="../../d6/df9/classcv_1_1ml_1_1LogisticRegression.html" title="Implements Logistic Regression classifier. ">cv::ml::LogisticRegression</a> </dd></dl>
</div></div><!-- contents -->
<!-- HTML footer for doxygen 1.8.6-->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Fri Apr 2 2021 11:36:33 for OpenCV by &#160;<a href="http://www.doxygen.org/index.html">
<img class="footer" src="../../doxygen.png" alt="doxygen"/>
</a> 1.8.13
</small></address>
<script type="text/javascript">
//<![CDATA[
addTutorialsButtons();
//]]>
</script>
</body>
</html>
